/**
 * Created by 张其川 on 2016/7/10.
 */



$(function () {
    //选择全部服务的复选框
    jQuery1_8("#selectAllServers").toggle(
        function () {
            $(".serverCheck").removeClass("glyphicon-unchecked").addClass("glyphicon-check");
            $(this).children("i").removeClass("glyphicon-unchecked").addClass("glyphicon-check");
        }, function () {
            $(".serverCheck").removeClass(" glyphicon-check").addClass("glyphicon-unchecked ");
            $(this).children("i").removeClass(" glyphicon-check").addClass("glyphicon-unchecked ");

        }
    );

})

//服务器的单个复选框点击事件处理
function selectServerCheck(team) {
    //team是td，td下面是span
    var span = $(team).children()[0];
    if ($(span).hasClass("glyphicon-unchecked")) {
        //如果点击的时候是未选中,那么就选中，
        $(span).removeClass("glyphicon-unchecked").addClass("glyphicon-check");
    }
    else {
        //如果是选中的，那么就取消选中
        $(span).removeClass("glyphicon-check").addClass("glyphicon-unchecked");
    }

}

function deleteServerConfigLine(deleteButton) {
    //删除服务器，请求服务服务器成功后，删除tr行
    var sid = deleteButton.getAttribute("sid");
    var td = $(deleteButton).parent();
    var tr = $(td).parent();
    $(tr).remove();//删除TR
    //从内存中删除记录
    for (var i = 0; i < window.allServersList.length; i++) {
        if (window.allServersList[i].id == sid) {
            window.allServersList.pop(i);
        }
    }
}

function deleteServerConfig(deleteButtonElements) {
    //deleteButtonElements=[deleteButton1,deleteButton2]
    //删除服务器，请求服务服务器
    var hosts = [];
    for (var i = 0; i < deleteButtonElements.length; i++) {
        hosts.push(deleteButtonElements[i].getAttribute("sid"));
	var sid=deleteButtonElements[i].getAttribute("sid");
    }
    var hostsData = JSON.stringify(hosts);
    jQuery.ajax({
        "url": deleteClassURL,
        "dataType": "jsonp",
        "data": {"sid": sid},
        "error": errorAjax,
        "beforeSend": start_load_pic,
        "complete": stop_load_pic,
        "success": function (data) {
            if (!data.status) {
                showErrorInfo(data.content);
                return false;
            }
            else {
                showSuccessNotic();
                //删除服务器表tr
                for (var i = 0; i < deleteButtonElements.length; i++) {
                    deleteServerConfigLine(deleteButtonElements[i]);
                }
		loadClassAdminToTab();

            }
        }

    });

}

function loadClassAdminToTable(editButton) {
    //editButton是编辑按钮
    //点击编辑按钮，把数据加载到编辑框中
    //首先显示编辑框
    startShadow();
    showEditServerConfigTable();//只是显示编辑框
    var data=editButton.getAttribute("data")
    data=JSON.parse(data)
    //把数据装载进入编辑框中的对象

    document.getElementById("name").value = data.name;//ip
    document.getElementById("description").value = data.description;

}


function showEditServerConfigTable() {
    //显示服务器编辑框
    $("#editServerConfigTable").animate({
        "left": "0px",
        "top": "0px",
    });
}


function loadServersConfigTable() {
    //显示服务器到表格中
    $("#serversConfigTbody").children().remove();//删除此前的HTML，这里有可能是加载刷新
    for (var i = 0; i < window.allServersList.length; i++) {
        var serverLine = window.allServersList[i];
        createServerLine(serverLine);//调用创建服务器的每一行
    }

}


function closeEditServer() {
    stopShadow();
    $("#editServerConfigTable").animate({
        "left": "100%",
        "top": "120%",
    })
}

//绑定编辑框中，各个按钮的事件
function changeServerDataButton() {
    //绑定选择密码登录方式的标签
    var password = document.getElementById("passwordDiv");//密码框


    //绑定别名唯一性检查


    //绑定sudo选择
    document.getElementById("sudo").onclick = function () {
        //this是div，
        sudoProgress(this)
    }
    //绑定su选择
    document.getElementById("su").onclick = function () {
        //this是div，
        suProgress(this)
    }
}
function createUserList() {
    //绑定用户归属选择
    var owner = document.getElementById("owner");
    for (var i = 0; i < window.userList.length; i++) {
        var username = window.userList[i];
        var option = document.createElement("option");
        option.value=username;
        option.textContent=username;
        if(window.whoami==username){
            //默认是当前用户
            option.setAttribute("selected","selected");
        }
        owner.appendChild(option);
    }
}


function cleanEditServerConfigTableData() {
    //清除编辑框的数据
    console.log(1111)
    document.getElementById("ip").value = "";
    document.getElementById("alias").value = "";
    document.getElementById("owner").innerHTML = '请选择 <span class="caret">';
    document.getElementById("group").value = "";
    document.getElementById("username").value = "";
    document.getElementById("port").value = 22;
    document.getElementById("sudo").value = sudo;
    $("#sudo").find("")
    document.getElementById("sudoPassword").value = sudoPassword;
    document.getElementById("su").value = su;
    document.getElementById("suPassword").value = ""
    document.getElementById("description").value = "";
}

function sudoProgress(div) {
    //点击sudo按钮的时候要处理的事情
    //div是i和span,i中是check
    var sudoPassword = document.getElementById("sudoPassword");
    var suPassword = document.getElementById("suPassword");

    var check = $(div).find("i")[0];
    if ($(check).hasClass("glyphicon-check")) {
        //如果点击之前是被选中的，则取消选中
        $(check).removeClass("glyphicon-check").addClass("glyphicon-unchecked")
        sudoPassword.setAttribute("disabled", true);//取消了以后，就不能输入密码了
    }
    else {
        $(check).removeClass("glyphicon-unchecked").addClass("glyphicon-check")
        sudoPassword.removeAttribute("disabled");
        //这里做了sudo的选中，所以取消su的选中
        var suDiv = $("#su");
        var suCheck = $(suDiv).find("i")[0];
        $(suCheck).removeClass("glyphicon-check").addClass("glyphicon-unchecked");
        suPassword.setAttribute("disabled", true)
    }

}
function suProgress(div) {
    //点击su按钮的时候要处理的事情
    var sudoPassword = document.getElementById("sudoPassword");
    var suPassword = document.getElementById("suPassword");
    //div是i和span,i中是check
    var check = $(div).find("i")[0];
    if ($(check).hasClass("glyphicon-check")) {
        //如果点击之前是被选中的，则取消选中
        $(check).removeClass("glyphicon-check").addClass("glyphicon-unchecked")
        suPassword.setAttribute("disabled", true)
    }
    else {
        $(check).removeClass("glyphicon-unchecked").addClass("glyphicon-check")
        suPassword.removeAttribute("disabled");
        //这里做了su的选中，所以取消sudo的选中
        var sudoDiv = $("#sudo");
        var sudoCheck = $(sudoDiv).find("i")[0];
        $(sudoCheck).removeClass("glyphicon-check").addClass("glyphicon-unchecked");
        sudoPassword.setAttribute("disabled", true)
    }

}



function getServerConfigFromTable() {
    //获取编辑框中的服务器配置
    var sid = document.getElementById("saveServerConfig").getAttribute("sid");
    var name = document.getElementById("name").value;
    var description=document.getElementById("description").value
    //填写的值检查
    if(/^ *$/.test(name)  ){
        showErrorInfo("请填写所有内容！");
        return false;
    }
    var serverConfig = {
        "id": sid,
        "name": name,
        "description": description,
    };
        var data = JSON.stringify(serverConfig);
        jQuery.ajax({
            "url": createClassAdminURL,
	    "type":$("#saveServerConfig").attr("type"),
            "data": {"data": data},
            "error": errorAjax,
            "beforeSend": start_load_pic,
            "complete": stop_load_pic,
            "success": function (data) {
		data=JSON.parse(data)
                if (!responseCheck(data)) {
                    showErrorInfo(data.content);
                    return false;
                }
                else {
			window.location.reload()
		
                }

            }
        });
        return true;
}


function modifyServerConfigTable(serverConfig) {
    //修改表格中的数据值
    console.log(serverConfig.name)
    var td = $(window.currentEditTr).parent();//Tr是一个editbutton
    var tr = $(td).parent();
    $(tr).find(".name")[0].textContent = serverConfig.name;
    $(tr).find(".description")[0].textContent = serverConfig.description;
    $(tr).find(".date")[0].textContent = serverConfig.date;
	console.log(serverConfig.date,111)


}



function batchCreateServers(){
	//批量创建服务器
	var info="#首先，以'#'开头的都是注释，系统将不解析这样的行。\n#第二，每一个字段请使用空格分开区分。\n#第三,服务器字段格式为(如果某字段为空值，请使用'#'占位,su和sudo字段请填写Y/N):"
	info += "\n#IP                别名     主机组 用户名  密码          端口 sudo sudo密码 su su密码 操作系统版本    备注"
	info += "\n#192.168.1.1 测试主机 测试组 admin  your-pass 22   N      #            N    #     CentOS5/Redhat5 某IDC机房"
	var textarea=document.getElementById("batchCreateServers");
	textarea.value=info;
}


function sendCreateServerRequest(){
    //获取批量数据发送到后端
    var textarea=document.getElementById("batchCreateServers").value;
    jQuery.ajax({
        "url":batchCreateServersURL,
        "type":"POST",
        "data":{"hosts":textarea},
        "beforeSend":start_load_pic,
        "complete":stop_load_pic,
        "error":errorAjax,
        "success":function(data){
            responseCheck(data);
            var data=JSON.parse(data);
            if(!data.status){
                showErrorInfo(data.content);
                return false;
            }
            else{
                var content=data.content;
                stopShadow();
                $("#batchServerDiv").hide("fast");
                //重新后台请求数据
                jQuery.ajax({
                    "url":loadServerListURL,
                    "dataType":"jsonp",
                    "error":errorAjax,
                    "beforeSend":start_load_pic,
                    "complete":stop_load_pic,
                    "success":function(data){
                        responseCheck(data);
                        if(!data.status){
                            showErrorInfo(data.content);
                            return false;
                        }
                        else{
                            window.allServersList=data.content;//更新缓存配置
                            loadServersConfigTable();
                            showSuccessNotic(content);
                        }
                    }
                });

            }
        }

    });
}





//初始化加载
//
function deleteClassAdmin(button) {
    //deleteButtonElements=[deleteButton1,deleteButton2]
    //删除服务器，请求服务服务器
	var sid=button.getAttribute("sid");
    jQuery.ajax({
        "url": deleteClassAdminURL,
        "dataType": "jsonp",
        "data": {"sid": sid},
        "error": errorAjax,
        "beforeSend": start_load_pic,
        "complete": stop_load_pic,
        "success": function (data) {
            if (!data.status) {
                showErrorInfo(data.content);
                return false;
            }
            else {
                showSuccessNotic();
		$(button).parent().parent().remove()
            }
        }

    });

}
function createClassAdminTab(data){
	var tbody=document.getElementById("classAdmintbody")
	var tr=document.createElement("tr")
	
	var td=document.createElement("td");
	td.textContent=data.sid;
	td.className="sid"
	tr.appendChild(td)

	var td=document.createElement("td");
	td.textContent=data.name;
	td.className="name"
	tr.appendChild(td)


	var td=document.createElement("td");
	td.textContent=data.date;
	td.className="date"
	tr.appendChild(td)

	var td=document.createElement("td");
	td.textContent=data.description;
	td.className="description"
	tr.appendChild(td)

	var td=document.createElement("td");
    var deleteButton = document.createElement("button");
    deleteButton.style.marginLeft = "3px";
    deleteButton.className = "btn btn-danger btn-xs";
    deleteButton.textContent="删除"
    deleteButton.setAttribute("sid", data.sid);
    deleteButton.onclick = function () {
        var t=confirm("真的要删除吗？")
        if(t===false){
		return false;
 	}

        deleteClassAdmin(this);
    }
    var editButton = document.createElement("button");
    editButton.className = "btn btn-primary btn-xs";
    editButton.textContent="编辑"
    editButton.setAttribute("sid", data.sid);//服务器的每一个参数在className中
    editButton.setAttribute("data", JSON.stringify(data));//服务器的每一个参数在className中
    editButton.onclick = function () {
        window.currentEditTr = this;//当前最的编辑行
        //把sid传递给保存按钮
        document.getElementById("saveServerConfig").setAttribute("sid", this.getAttribute("sid"));
        document.getElementById("saveServerConfig").setAttribute("type", "PUT");
        loadClassAdminToTable(this)

    }
    td.appendChild(editButton);

    var viewButton = document.createElement("a");
    viewButton.className = "btn btn-success btn-xs";
    viewButton.textContent="学生列表"
    viewButton.setAttribute("sid", data.sid);//服务器的每一个参数在className中
    viewButton.setAttribute("href","cheungssh.html?page=students.html&sid="+data.sid)
    viewButton.style.marginLeft="3px"
    td.appendChild(viewButton);


    td.appendChild(deleteButton);
    tr.appendChild(td);



	tbody.appendChild(tr)
}
function loadClassAdminToTab(){
	jQuery.ajax({
		"url":getClassAdminURL,
		"dataType":"jsonp",
		"error":errorAjax,
		"sendBefore":start_load_pic,
		"complete":stop_load_pic,
		"success":function(data){
			console.log(data)

			if(!data.status){
				showErrorInfo(data.content);
			}
			else{
				for(i=0;i<data.content.length;i++){
					createClassAdminTab(data.content[i]);
				}
			}
		}
	})
}

loadClassAdminToTab();
$(function () {//c



    //批量创建
    //加载服务器
    //绑定关闭编辑服务器按钮
    document.getElementById("closeEditServer").onclick = function () {
        closeEditServer();
    }
    //绑定编辑框中的各种事件
    changeServerDataButton();
    //绑定创建服务器
    document.getElementById("createClass").onclick = function () {
        startShadow();
	document.getElementById("description").value = "";
	document.getElementById("name").value = "";
        showEditServerConfigTable();//显示服务器编辑框
	$("#saveServerConfig").attr("type","POST")
    }
    //绑定保存服务器配置按钮
    document.getElementById("saveServerConfig").onclick = function () {

        if (getServerConfigFromTable()) {
            //获取编辑框中的值
            closeEditServer();//最后关闭编辑框
        }
    }

    //绑定关闭显示检查服务器信息的按钮
    document.getElementById("closeCheckInfo").onclick=function(){
        $("#showServerCheckInfo").hide("fast");
        stopShadow();
    }
	//绑定批量创建DIv
	//最后批量穿件按钮
    document.getElementById("createServers").onclick=function(){
        sendCreateServerRequest();//发送数据到后端
    }

    //createServerAndDevice();//加载设备连接列表


})



